<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" size="mini">
            <el-form-item label="患者账号" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入患者账号" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="患者姓名" prop="nickName">
                <el-input v-model="queryParams.nickName" placeholder="请输入患者姓名" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
                <el-date-picker v-model="birthdayRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="联系方式" prop="phonenumber">
                <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 150px;" @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="患者状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="患者状态" clearable style="width: 120px;">
                    <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="所属职称">
                <el-select v-model="queryParams.params.post" placeholder="请选择职称" style="width: 150px;" clearable>
                    <el-option v-for="dict in dict.type.basic_post_simulated_patient_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="国籍">
                <el-select v-model="queryParams.params.nationality" placeholder="请选择国籍" style="width: 150px;" clearable>
                    <el-option v-for="dict in dict.type.basic_nationality_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" clearable range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:simulated_patient:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImport" v-hasPermi="['system:simulated_patient:import']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:simulated_patient:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" :height="table_height">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="患者账号" align="center" key="userName" prop="userName" show-overflow-tooltip/>
            <el-table-column label="患者姓名" align="center" key="nickName" prop="nickName" show-overflow-tooltip/>
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" show-overflow-tooltip/>
            <el-table-column label="身份证" align="center" key="identity" prop="identity" show-overflow-tooltip/>
            <el-table-column label="邮箱" align="center" key="email" prop="email" show-overflow-tooltip/>
            <el-table-column label="生日" align="center" prop="birthday" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.birthday,'{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="性别" align="center" key="sex" prop="sex">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
                </template>
            </el-table-column>
            <el-table-column label="身高(cm)" align="center" key="userInfo.height" prop="userInfo.height" show-overflow-tooltip/>
            <el-table-column label="体重(kg)" align="center" key="userInfo.weight" prop="userInfo.weight" show-overflow-tooltip/>
            <el-table-column label="职称" align="center" key="userInfo.post" show-overflow-tooltip>
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_post_simulated_patient_dict" :value="scope.row.userInfo.post"/>
                </template>
            </el-table-column>
            <el-table-column label="国籍" align="center" key="userInfo.nationality">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_nationality_dict" :value="scope.row.userInfo.nationality"/>
                </template>
            </el-table-column>
            <el-table-column label="婚姻状态" align="center" key="userInfo.marital">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.basic_marital_dict" :value="scope.row.userInfo.marital"/>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" key="status">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" inactive-color="red" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime,'{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                        <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改患者配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row v-if="form.userId == undefined">
                    <el-col :span="12">
                        <el-form-item label="患者账号" prop="userName">
                            <el-input v-model="form.userName" placeholder="请输入患者账号" maxlength="30" style="width: 220px" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="患者密码" prop="password">
                            <el-input v-model="form.password" placeholder="请输入患者密码" type="password" maxlength="20" show-password style="width: 220px" clearable/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="患者姓名" prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入患者姓名" maxlength="30" style="width: 220px" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phonenumber">
                            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" style="width: 220px"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="身份证" prop="identity">
                            <el-input v-model="form.identity" placeholder="请输入身份证" maxlength="32" style="width: 220px"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="生日">
                            <el-date-picker v-model="form.birthday" type="date" value-format="yyyy-MM-dd"  placeholder="请选择生日" style="width: 220px"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="30" style="width: 220px"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="患者性别">
                            <el-radio-group v-model="form.sex">
                                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="婚姻状态">
                            <el-radio-group v-model="form.userInfo.marital">
                                <el-radio v-for="dict in dict.type.basic_marital_dict" :key="parseInt(dict.value)" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="职称">
                            <el-select v-model="form.userInfo.post" placeholder="请选择职称" style="width: 220px" clearable>
                                <el-option v-for="dict in dict.type.basic_post_simulated_patient_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="国籍">
                            <el-select v-model="form.userInfo.nationality" placeholder="请选择国籍" style="width: 220px" clearable>
                                <el-option v-for="dict in dict.type.basic_nationality_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="身高(cm)">
                            <el-input-number v-model="form.userInfo.height" :precision="2" :step="0.2" style="width: 220px"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="体重(kg)">
                            <el-input-number v-model="form.userInfo.weight" :precision="2" :step="0.2" style="width: 220px"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="22">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 患者导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
                       :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport"/>
                        是否更新已经存在的患者数据
                    </div>
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {getUser, delUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect} from "@/api/system/user";
import {addSimulatedPatient, listSimulatedPatient} from "@/api/system/simulated_patient";
import {getToken} from "@/utils/auth";
import {copyObj} from "@/utils/zzDouUtils/objUtil";
import {nowDateStr} from "@/utils/zzDouUtils/dateUtil";

var pageForm = {pageSize:1000,pageNum:1}
export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex','basic_post_simulated_patient_dict','basic_nationality_dict','basic_marital_dict'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 患者表格数据
            userList: null,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 科室账号
            deptName: undefined,
            // 默认密码
            initPassword: undefined,
            // 日期范围
            dateRange: [],
            birthdayRange: [],
            // 岗位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            form: {
                userInfo:{},
            },
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 患者导入参数
            upload: {
                // 是否显示弹出层（患者导入）
                open: false,
                // 弹出层标题（患者导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的患者数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/system/simulated-patient/importData"
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                phonenumber: null,
                status: null,
                deptId: null,
                params:{},
            },
            // 表单校验
            rules: {
                userName: [
                    {required: true, message: "患者账号不能为空", trigger: "blur"},
                    {min: 2, max: 20, message: '患者账号长度必须介于 2 和 20 之间', trigger: 'blur'}
                ],
                nickName: [
                    {required: true, message: "患者姓名不能为空", trigger: "blur"}
                ],
                password: [
                    {required: true, message: "患者密码不能为空", trigger: "blur"},
                    {min: 5, max: 20, message: '患者密码长度必须介于 5 和 20 之间', trigger: 'blur'}
                ],
                email: [
                    {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
                ],
                phonenumber: [
                    {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                ],
                identity: [
                    {pattern: /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号", trigger: "blur"}
                ]
            }
        };
    },
    watch: {
        // 根据账号筛选科室树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getList();
        this.getDeptTree();
        this.getConfigKey("sys.user.initPassword").then(response => {
            this.initPassword = response.msg;
        });
    },
    methods: {
        /** 查询患者列表 */
        getList() {
            this.loading = true;
            let data = this.addDateRange(this.queryParams, this.dateRange); //创建时间
            data = this.addDateRange(this.queryParams, this.birthdayRange,'Birthday'); //生日
            listSimulatedPatient(data).then(response => {
                    this.userList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                }
            );
        },
        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id;
            this.handleQuery();
        },
        // 患者状态修改
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要 ' + text + ' ' + row.nickName + ' 患者吗？').then(function () {
                return changeUserStatus(row.userId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: null,
                deptId: null,
                userName: null,
                nickName: null,
                password:  this.initPassword,
                phonenumber: null,
                email: null,
                sex: null,
                status: "0",
                remark: null,
                postIds: [],
                roleIds: [],
                userInfo:{
                    height: 160.00,
                    weight: 50.00
                },
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                userName: null,
                phonenumber: null,
                status: null,
                deptId: null,
                params:{},
            };
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleResetPwd":
                    this.handleResetPwd(row);
                    break;
                case "handleAuthRole":
                    this.handleAuthRole(row);
                    break;
                default:
                    break;
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            getUser().then(response => {
                // this.postOptions = response.posts;
                // this.roleOptions = response.roles;
                this.open = true;
                this.title = "添加患者";
                this.form.password = this.initPassword;
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = copyObj(row);
            this.form.userInfo = copyObj(row.userInfo)
            this.open = true;
            this.title = "修改患者";
            this.form.password = null;
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: "患者密码长度必须介于 5 和 20 之间"
            }).then(({value}) => {
                resetUserPwd(row.userId, value).then(response => {
                    this.$modal.msgSuccess("修改成功，新密码是：" + value);
                });
            }).catch(() => {
            });
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId;
            this.$router.push("/system/user-auth/role/" + userId);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.userId != undefined) {
                        updateUser(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addSimulatedPatient(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids;
            this.$modal.confirm('是否确认删除患者编号为"' + userIds + '"的数据项？').then(function () {
                return delUser(userIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/simulated-patient/export', {
                ...this.queryParams
            }, `患者_${nowDateStr()}.xlsx`)
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "患者导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('system/simulated-patient/importTemplate', {}, `患者模板_${nowDateStr()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
    }
};
</script>
